/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dto.Account;
import dto.Message;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

/**
 *
 * @author Motaz
 */
public class MessageDAO extends AbstractDAO {

    AccountDAO accountDAO = new AccountDAO();
    
    public void saveMessage(Message message, Account member) throws SQLException {
        PreparedStatement stmt = connection.prepareStatement("INSERT INTO message (account, `from`, `date`, body) VALUES (?, ?, ?, ?)");
        
        
        stmt.setInt(1, accountDAO.getAccountId(member.getEmail()));
        stmt.setInt(2, accountDAO.getAccountId(message.getFrom().getEmail()));
        stmt.setDate(3, new Date(message.getDate().getTime()));
        stmt.setString(4, message.getBody());
        
        stmt.execute();
    }
    
    
    public Vector<Message> getMessages(int id) throws SQLException {
        PreparedStatement stmt = connection.prepareStatement("SELECT * from message WHERE account = ? order by `from`");
        
        stmt.setInt(1, id);
        
        Vector<Message> messages = new Vector<>();
        ResultSet rs = stmt.executeQuery();
        while(rs.next()) {
            Message message = new Message();
            
            message.setFrom(accountDAO.getAccount(rs.getInt("from")));
            message.setTo(accountDAO.getAccount(rs.getInt("account")));
            message.setBody(rs.getString("body"));
            message.setDate(rs.getDate("date"));
            
            messages.add(message);
        }
        return messages;
    } 

    public void deleteMessages(int id) throws SQLException {
        PreparedStatement stmt = connection.prepareStatement("DELETE from message WHERE account = ?");
        stmt.setInt(1, id);
        stmt.execute();
    }
}
